<template>
  <div class="main">
    <h1>全民房东管家</h1>
    <a-form id="formLogin" class="user-layout-login" ref="formLogin" :form="form" @submit="handleSubmit">
      <a-form-item>
        <a-input
          maxLength="11"
          size="large"
          type="text"
          placeholder="手机号"
          v-decorator="['mobile', {rules: [{ required: true, pattern: phoneReg, message: '请输入正确的手机号' }], validateTrigger: 'change'}]">
          <a-icon slot="prefix" type="mobile" :style="{ color: 'rgba(0,0,0,.25)' }" />
        </a-input>
      </a-form-item>
      <a-row :gutter="16">
        <a-col class="gutter-row" :span="16">
          <a-form-item>
            <a-input
              maxLength="6"
              size="large"
              type="text"
              placeholder="验证码"
              v-decorator="['captcha', {rules: [{ required: true, pattern: /^\d{6}$/, message: '请输入正确的验证码' }], validateTrigger: 'change'}]">
              <a-icon slot="prefix" type="mail" :style="{ color: 'rgba(0,0,0,.25)' }" />
            </a-input>
          </a-form-item>
        </a-col>
        <a-col class="gutter-row" :span="8">
          <a-button
            class="getCaptcha"
            tabindex="-1"
            :disabled="state.smsSendBtn"
            @click.stop.prevent="getCaptcha"
            v-text="!state.smsSendBtn && '获取验证码' || (state.time+' s')"></a-button>
        </a-col>
      </a-row>
      <a-form-item style="margin-top:24px">
        <a-button
          size="large"
          type="primary"
          htmlType="submit"
          class="login-button"
          :loading="state.loginBtn"
          :disabled="state.loginBtn">登录</a-button>
      </a-form-item>
    </a-form>
    <two-step-captcha
      v-if="requiredTwoStepCaptcha"
      :visible="stepCaptchaVisible"
      @success="stepCaptchaSuccess"
      @cancel="stepCaptchaCancel"></two-step-captcha>
    <a-modal
      title="提示"
      v-model="warning"
      :centered="true"
      :footer="null"
      width="auto"
    >
      <div class="warning" style="padding:60px 76px;display: flex;align-items:center">
        <div>
          <p class="font16 color0">手机号未注册</p>
          <p class="color3">请先通过微信搜索或扫描右侧二维码打开小程序“在线前台房东端”，注册并认证。</p>
        </div>
        <div style="padding-left:84px;"><img src="../../assets/weixin.png" alt="" style="width:164px;height:180px;"></div>
      </div>
    </a-modal>
  </div>
</template>

<script>
// import md5 from 'md5'
import { phoneReg } from '@/utils/reg'
import TwoStepCaptcha from '@/components/tools/TwoStepCaptcha'
import { mapActions } from 'vuex'
import { timeFix } from '@/utils/util'
// import { getSmsCaptcha, get2step } from '@/api/login'
// 以下为去掉路由权限
import { getSmsCaptcha } from '@/api/login'
export default {
  components: {
    TwoStepCaptcha
  },
  data () {
    return {
      phoneReg,
      warning: false, //  未注册提示
      customActiveKey: 'tab2',
      loginBtn: false,
      // login type: 0 email, 1 username, 2 telephone
      loginType: 0,
      requiredTwoStepCaptcha: false,
      stepCaptchaVisible: false,
      form: this.$form.createForm(this),
      state: {
        time: 60,
        loginBtn: false,
        // login type: 0 email, 1 username, 2 telephone
        loginType: 0,
        smsSendBtn: false
      }
    }
  },
  created () {
    // get2step({ })
    //   .then(res => {
    //     this.requiredTwoStepCaptcha = res.result.stepCode
    //   })
    //   .catch(() => {
    //     this.requiredTwoStepCaptcha = false
    //   })
    // this.requiredTwoStepCaptcha = true
  },
  methods: {
    ...mapActions(['Login', 'Logout']),
    // handler
    handleUsernameOrEmail (rule, value, callback) {
      const { state } = this
      const regex = /^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+((\.[a-zA-Z0-9_-]{2,3}){1,2})$/
      if (regex.test(value)) {
        state.loginType = 0
      } else {
        state.loginType = 1
      }
      callback()
    },
    handleTabClick (key) {
      this.customActiveKey = key
      // this.form.resetFields()
    },
    // 登录
    handleSubmit (e) {
      e.preventDefault()
      const {
        form: { validateFields },
        state,
        customActiveKey,
        Login
      } = this

      state.loginBtn = true

      const validateFieldsKey = customActiveKey === 'tab1' ? ['username', 'password'] : ['mobile', 'captcha']

      validateFields(validateFieldsKey, { force: true }, (err, values) => {
        if (!err) {
          // const loginParams = { ...values }
          // delete loginParams.username
          // loginParams[!state.loginType ? 'email' : 'username'] = values.username
          // loginParams.password = md5(values.password)
          const phoneParams = {
            code: values.captcha,
            phone: values.mobile
          }
          // Login(qs.stringify(phoneParams))
          Login(phoneParams)
            .then((res) => this.loginSuccess(res))
            .catch(err => this.requestFailed(err))
            .finally(() => {
              state.loginBtn = false
            })
        } else {
          setTimeout(() => {
            state.loginBtn = false
          }, 600)
        }
      })
    },
    getCaptcha (e) {
      e.preventDefault()
      const { form: { validateFields }, state } = this

      validateFields(['mobile'], { force: true }, (err, values) => {
        if (!err) {
          state.smsSendBtn = true
          const interval = window.setInterval(() => {
            if (state.time-- <= 0) {
              state.time = 60
              state.smsSendBtn = false
              window.clearInterval(interval)
            }
          }, 1000)
          const hide = this.$message.loading('验证码发送中..', 0)
          getSmsCaptcha({ phone: values.mobile }).then(res => {
            setTimeout(hide, 2500)
            if (res.code === 200) {
              this.$notification['success']({
                message: this.$t('message.successTitle'),
                description: res.message,
                // description: '验证码获取成功，您的验证码为：' + res.result.captcha,
                duration: 8
              })
            } else {
              this.$notification['error']({
                message: this.$t('message.errorTitle'),
                description: res.message,
                duration: 8
              })
            }
          }).catch(err => {
            setTimeout(hide, 1)
            clearInterval(interval)
            state.time = 60
            state.smsSendBtn = false
            this.requestFailed(err)
          })
        }
      })
    },
    stepCaptchaSuccess () {
      this.loginSuccess()
    },
    stepCaptchaCancel () {
      this.Logout().then(() => {
        this.loginBtn = false
        this.stepCaptchaVisible = false
      })
    },
    loginSuccess (res) {
      if (res.code === 2021) {
        // 未注册弹窗提示
        this.warning = true
      } else {
        this.$router.push({ name: 'dashboard' })
        // 延迟 1 秒显示欢迎信息
        setTimeout(() => {
          this.$notification.success({
            message: '欢迎',
            description: `${timeFix()}，欢迎回来`
          })
        }, 1000)
      }
    },
    requestFailed () {
      // this.$notification['error']({
      //   message: this.$t('message.errorTitle'),
      //   description: ((err.response || {}).data || {}).message || this.$t('message.errorMsg'),
      //   duration: 4
      // })
    }
  }
}
</script>

<style lang="less" scoped>
.main {
  height: 343px;
  // width: 352px !important;
  background-color: #FFFFFFFE;
  border-radius: 15px;
  position: absolute;
  right: 20%;
  padding: 15px;
  top:50%;
  margin-top: -172px !important;
  ;
  h1 {
    font-size: 26px;
    margin: 20px;
    text-align: center;
  }

  .user-layout-login {
  label {
    font-size: 14px;
  }

  .getCaptcha {
    display: block;
    width: 100%;
    height: 40px;
  }

  .forge-password {
    font-size: 14px;
  }
  button.login-button {
    padding: 0 15px;
    font-size: 16px;
    height: 40px;
    width: 100%;
  }
  .user-login-other {
    text-align: left;
    margin-top: 24px;
    line-height: 22px;
    .item-icon {
      font-size: 24px;
      color: rgba(0, 0, 0, 0.2);
      margin-left: 16px;
      vertical-align: middle;
      cursor: pointer;
      transition: color 0.3s;

      &:hover {
        color: #1890ff;
      }
    }
    .register {
      float: right;
    }
  }
}
}

</style>
